import React, { Component } from 'react';
import {
    View,
    StyleSheet,
    RefreshControl,
    DeviceEventEmitter,
    Image
} from 'react-native';

import {
    Container,
    Content,
    Card,
    CardItem,
    Left,
    Thumbnail,
    Text,
    Body,
    Icon,
    Badge,
    Spinner
} from 'native-base';
import { NavigationActions } from 'react-navigation';

import STRING from '../../const_string_zh_CN';
import URL from '../../net/url.js';
import { connect } from 'react-redux';
import Message from '../../net/message.js';
import CourseMessage from '../../db/course_message_table.js';

class tab_message extends Component {
    constructor(props) {
        super(props);
        this.state = {
            school_data: null,
            course_data: null,
            schoolTitle: null,
            courseTitle: null,
        };
    }

    render() {
        const { navigate } = this.props.navigation;
        // const {MessageList} = this.props;
        const { CourseMessageList } = this.props;
        //需要判断

        return (
            <Content refreshControl={<RefreshControl refreshing={false} />} scrollEnabled={true}>
                <Card style={StyleSheet.flatten(styles.card_style)}>
                    <CardItem footer bordered button onPress={() => {
                        navigate('MessageListTab', { title: "学校通知" });

                    }}>
                        <Left>
                            <Thumbnail square source={require('../../images/course.png')} />
                            <Body>
                                <Text>学校通知</Text>
                                <Text note>学校通知</Text>
                            </Body>
                        </Left>
                        <Image style={StyleSheet.flatten(styles.backIcon)} source={require('../../images/back.png')} />
                        {/* <Icon name="arrow-forward" /> */}
                    </CardItem>

                    <CardItem footer bordered button onPress={() => {
                        navigate('MessageCourseListTab', { title: "课堂通知" });
                        CourseMessageList({
                            type: 'CourseMessageList',
                            payload: {
                                course_data: this.state.course_data,
                            }
                        });
                    }}>
                        <Left>
                            <Thumbnail square source={require('../../images/course.png')} />
                            <Body>
                                <Text>课堂通知</Text>
                                <Text note>课堂通知</Text>
                            </Body>
                        </Left>
                        <Image style={StyleSheet.flatten(styles.backIcon)} source={require('../../images/back.png')} />
                        {/* <Icon name="arrow-forward" /> */}
                    </CardItem>

                </Card>
            </Content>
        );
    }
    //加载等待的view
    renderLoadingView() {
        return (
            <Container>
                <Content>
                    <Spinner color='green' />
                </Content>
            </Container>
        );
    }
    //rn的生命周期，初始化的时候会执行
    async componentWillMount() {
        const { login_info } = this.props;
        let message = new Message();
        let message_info=new CourseMessage();
        // var mytitle='暂无信息';
        //1为学校通知，2为课程通知
        // let schollMess=await message.getMessageList(login_info.userName,1);
        // let courseData = await message.getMessageList(login_info.userName,2);
        // let messNum=await message.getUnreadMessageNum(login_info.userName,2,0);//未读消息
        // console.log('unread:',messNum);
        // console.log('obj');
        // console.log(schollMess);

        //推送消息监听事件，获取数据为object
        this.subscription = DeviceEventEmitter.addListener('mipush', (events) => {
            let datatemp = JSON.parse(events.data);
            console.log('datatemp');
            console.log(datatemp);
            let args = [datatemp];

            try {
                let createTable=message_info.createCourseMessageTable();
                console.log('courseInMessageTable------------------');
                console.log('createTable----:',createTable);
                let OnlineClassID=null;
                let SendSubjectID=null;
                let SubjectID=null;
                let classid=decodeURI(datatemp.class);
                let coursetitle=decodeURI(datatemp.coursetitle);
                let messageType=datatemp.messageType;
                let moocCourseID=datatemp.moocCourseID;
                let sendtime=datatemp.sendtime;
                let teacher=decodeURI(datatemp.teacher);
                let singstatus='0';//签到状态，0表示未签到，1表示签到
                if(messageType=='interaction'){
                    OnlineClassID=datatemp.OnlineClassID;
                    SendSubjectID=datatemp.SendSubjectID;
                    SubjectID=datatemp.SubjectID;
                }
                let insertResult=message_info.insertCourseMessage(OnlineClassID,SendSubjectID,SubjectID,classid,coursetitle,messageType,moocCourseID,sendtime,teacher,singstatus);
                console.log('insertResult--------------:',insertResult) 
            } catch (e) {
                console.log("error", e);
            } 
            console.log('received data-----:',datatemp);
            this.setState({
                course_data: args,
            });
            if (args[0].messageType == 'interaction') {
                const { InteractionPushSubjectId } = this.props;
                InteractionPushSubjectId({
                    type: 'InteractionPushSubjectId',
                    payload: {
                        subjectId: args[0].SubjectID,
                        OnlineClassID: args[0].OnlineClassID,
                        //题目推送号
                        SendSubjectID: args[0].SendSubjectID,
                    }
                });
                this.props.navigation.navigate('QuestionStudent_course', { title: decodeURI(args[0].coursetitle) });
            }

        });
    }

    componentWillUnmount() {
        this.subscription.remove();
    }
}

const styles = StyleSheet.create({
    card_style: {
        marginRight: 0,
        marginLeft: 0,
        marginTop: 0,
        marginBottom: 0,
    },
    backIcon: {
        width: 20,
        height: 20,
        // marginLeft:'63%',
        marginRight: '5%',
        opacity: 0.6,

    },
    list_item: {
        marginLeft: 0,
        backgroundColor: '#ffffff',
        height: 50,
        padding: 15,
        borderBottomWidth: 0.2,
        borderBottomColor: "#cac0c0",
        borderTopColor: "#cac0c0",
        // borderTopWidth: 0.5,
        //textAlign: 'justify',
        //fontFamily: '微软雅黑',
    },
});

//从公共reducers获取数据login_info
function mapStateToProps(state) {
    return {
        login_info: state.login.login_info
    }
}

//将获取的数据抛给reducers
function mapDispatchToProps(dispatch) {
    return {
        CourseMessageList: (state) => dispatch(state),
        InteractionPushSubjectId: (state) => dispatch(state),
    }
}

const DiscoveryInteract = connect(
    mapStateToProps,
    mapDispatchToProps
)(tab_message)

export default DiscoveryInteract;
